package com.tang.controller;

import com.tang.entity.Book;
import com.tang.entity.Borrow;
import com.tang.entity.Reader;
import com.tang.service.BookService;
import com.tang.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author tang
 * @create 2020-09-14
 */

/**
 * 响应读者端的操作
 */
@WebServlet("/reader")
public class ReaderServlet extends HttpServlet {
    BookService bookService = new BookServiceImpl();
    private final int LIMIT = 10;
    private final int pages = bookService.findAll(LIMIT);

    /**
     * 查找所有书籍，查看借书记录，借书申请
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        HttpSession session = req.getSession();

        if (method == null) {
            method = "find";
        }

        switch (method) {
            //查询所有书本信息
            case "find":
                String pageStr = req.getParameter("page");
                Integer page = Integer.parseInt(pageStr);

                int index = (page - 1) * LIMIT;
                List<Book> list = bookService.find(index, LIMIT);
                req.setAttribute("list", list);
                req.setAttribute("currentPage", page);
                req.setAttribute("pages", pages);
                req.setAttribute("dataPrePage", LIMIT);
                req.getRequestDispatcher("index.jsp").forward(req, resp);
                break;

            case "addBorrow":
                //添加一条借书记录
                Reader reader = (Reader) session.getAttribute("reader");
                int readerId = reader.getId();

                String bookIdStr = req.getParameter("bookid");
                Integer bookId = Integer.parseInt(bookIdStr);
                bookService.addBorrow(readerId, bookId);

                List<Borrow> borrowList = bookService.query(readerId);
                req.setAttribute("list", borrowList);
                System.out.println(borrowList);
                req.getRequestDispatcher("borrow.jsp").forward(req, resp);
                break;

            case "query":
                //展示当前用户所有借书记录
                Reader reader2 = (Reader) session.getAttribute("reader");
                int readerId2 = reader2.getId();
                List<Borrow> borrowList2 = bookService.query(readerId2);

                req.setAttribute("list", borrowList2);
                System.out.println(borrowList2);
                req.getRequestDispatcher("borrow.jsp").forward(req, resp);
        }
    }
}
